<template>
  <div class="upload-container">
    <input type="file" @change="fileOnChange" id="fileInput" :accept="accept" style="display: none"/>
    <el-dialog :visible.sync="isDialog" title="上传列表" class="myDialog">
      <div v-show=" this.projectId" @click="selectFile">
        <div>
          <div
              class="drop-zone"
              @dragover.prevent="onDragOver"
              @drop.prevent="onDrop"
          >
            <i class="el-icon-upload" style="font-size: 24px;margin-right:8px"></i>
            <div class="el-upload__text">将文件拖到此处，或<em style="color:#1E6FFF">点击上传</em></div>
          </div>
        </div>
      </div>
      <div style="margin-top: 24px">
        <div v-for="(item,index) in fileList" :key="index" style="padding-bottom:14px">
          <div >
            <span style="font-size: 14px;">{{ item.file.name }}</span>
            <span style="margin-left:10px;font-size: 14px;">{{ item.size }}M</span>
            <span style="margin-left:20px;color: #1E6FFF">{{ item.uploadStateTxt }} {{ item.uploadProgres }}</span>
            <el-button v-show="item.loadingShow" :loading="true" type="text"></el-button>
          </div>
          <el-row style="rowCenter">
            <el-col :span="20">
              <el-progress style="" :text-inside="true" :stroke-width="18" :percentage="item.uploadProgress"></el-progress>
            </el-col>
            <el-col :span="2" >
              <img class="imgSize" v-show="item.uploadBtnShow" src="@/assets/images/gzq/icon-upload.png" alt="" @click="uploadFile(item)">
            </el-col>
            <el-col :span="1" >
              <img class="imgSize" src="@/assets/images/gzq/icon-del2.png" alt="" @click="deleteFile(item)">
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import {getPreSignedUrl2upload, projectFileAdd} from "../../api/upload";
import axios from "axios";
export default {
  name: 'ChunkUpload',
  props: {
    iconShow: {
      type: Boolean,
      default: true,
    },
    accept: {
      type: String,
      default: null,
    },
    disabled: Boolean,
    limit: {
      type: Number,
      default: 5,
    },
    chunkSize: {
      type: Number,
      default: 5 * 1024 * 1024,
    },
    thread: {
      type: Number,
      default: 1,
    },
    beforeUpload: {
      type: Function,
      default: () => {
      },
    },
    beforeRemove: {
      type: Function,
      default: () => {
      },
    },
    onRemove: {
      type: Function,
      default: () => {
      },
    },
    onChange: {
      type: Function,
      default: () => {
      },
    },
    onSuccess: {
      type: Function,
      default: () => {
      },
    },
    onProgress: {
      type: Function,
      default: () => {
      },
    },
    onError: {
      type: Function,
      default: () => {
      },
    },
  },
  data() {
    return {
      isDialog: false,
      fileList: [],
      projectId: null,
    }
  },
  mounted() {
    // 声音提示
    this.$bus.$off('minioSelectFile')
    this.$bus.$on('minioSelectFile', (projectId) => {
      this.projectId = projectId;
      this.isDialog = true;
      // this.selectFile()
    })
  },
  methods: {
    onDragOver(event) {
      event.preventDefault();
      event.stopPropagation();
    },
    onDrop(event) {
      event.preventDefault();
      event.stopPropagation();
      const files = event.dataTransfer.files;
      if (files.length > 0) {
        let file = files[0];
        this.pushFile(file);
      }
    },
    selectFile() {
      document.querySelector('#fileInput').click();
    },
    setDialog(open) {
      this.isDialog = open;
    },
    fileOnChange() {
      let file = document.querySelector('#fileInput').files[0];
      this.pushFile(file);
      this.isDialog = true;
    },
    pushFile(file) {
      // 检查是否已经选中
      if (this.checkFileByName(file.name) !== -1) {
        this.clearFileInput();
        this.msgInfo("文件已存在!")
        return
      }
      this.onChange(file);
      let fileInfo = {
        projectId: this.projectId,
        file: file,
        name: file.name,
        length: file.size,
        size: (file.size / (1024 * 1024)).toFixed(2),
        contentType: file.type,
        chunks: [],
        chunkTotal: Math.ceil(file.size / this.chunkSize),
        uploadProgress: 0,
        uploadStateTxt: "待上传...",
        uploadState: 1,  // 1  待上传 2 上传中 3 上传完成
        loadingShow: false,
        uploadBtnShow: true,
        ifUploadFinish: false,
      }
      this.fileList.push(fileInfo);
      this.isDialog = true;
    },
    // 上传文件
    async uploadFile(fileInfo) {
      this.beforeUpload();
      fileInfo.uploadStateTxt = "正在上传...";
      fileInfo.uploadState = 2;
      fileInfo.loadingShow = true;
      fileInfo.uploadBtnShow = false
      const data = await getPreSignedUrl2upload({"projectId": fileInfo.projectId, "fileName": fileInfo.name});
      fileInfo.preSignedUrl = data.url;
      fileInfo.cancelSource = axios.CancelToken.source();

      const formData = new FormData();
      formData.append('file', fileInfo.file);
      const config = {
        headers: {
          'Content-Type': fileInfo.file.type || 'application/octet-stream'
        },
        onUploadProgress: (progressEvent) => { // 上传进度
          fileInfo.uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        },
        cancelToken: fileInfo.cancelSource.token,
      };
      try {
        await axios.put(fileInfo.preSignedUrl, fileInfo.file, config); // 上传
        // 上传成功后保存 数据
        projectFileAdd({
          projectId: fileInfo.projectId,
          name: fileInfo.name,
          contentType: fileInfo.contentType,
          size: fileInfo.length,
          path: data.path
        }).then(res => {
          sessionStorage.setItem('projectId', fileInfo.projectId);
          document.querySelector('#fileInput').value = null;
          fileInfo.uploadStateTxt = "上传完成！";
          fileInfo.uploadState = 3;
          fileInfo.ifUploadFinish = true;
          fileInfo.loadingShow = false;
          fileInfo.uploadBtnShow = false;
          this.onSuccess(res.data);
        })
      } catch (error) {
        this.onError(error);
      }
    },
    checkFileByName(fileName) {
      return this.fileList.findIndex(item => item.name === fileName)
    },
    // 清空 fileInput
    clearFileInput() {
      document.querySelector('#fileInput').value = null;
    },
    // 删除文件
    deleteFile(fileInfo) {
      this.fileList.splice(this.fileList.findIndex(item => item.name === fileInfo.name), 1)
      if (this.fileList.length === 0) {
        this.isDialog = false;
      }
      this.cancelUpload(fileInfo);
    },
    cancelUpload(fileInfo) {
      if (fileInfo.cancelSource) {
        fileInfo.cancelSource.cancel('Upload canceled by user.');
        fileInfo.cancelSource = null;
      }
    },
  }
}
</script>

<style scoped lang="scss">
.upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 148px;
  height: 148px;
  background-color: #fbfdff
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.drop-zone {
  /* width: 808px; */
  height: 80px;
  border-radius: 2px;
  border: 1px dashed #828283;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  padding: 28px 0;
}

.myDialog {
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 3%;
  .dialog-footer{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  /deep/.el-dialog{
    width: 600px;
    min-height: 400px;
    display: flex;
    flex-direction: column;
    background-repeat: no-repeat;
    background-size: 100%;
  }

  /deep/.el-dialog__header{
    // padding: 17px 40px;
    padding: 16px 20px 16px 15px;
    color: #97ddfb;
    // border-radius: 8px 8px 0 0;
    // background-image: url('../../../assets/images/headDialog.png');
    // background-repeat: no-repeat;
    // background-position:center;
    // // background-size: 100% 100%;
    // background-size: cover;
    // font-weight: bold;
    font-size: 18px;
    // background: #193f54;
    border-bottom: 1px solid #FFFFFF;
  }
  /deep/.el-dialog__title{
    color: #1c1c1c;
    font-family: "Alibaba PuHuiTi 3.0";
    font-weight: 500;
    font-size: 16px;
    display: flex;
    align-items: center;

    &::before{
      content: '';
      display: block;
      // width: 10px;
      // height: 10px;
      // border: 2px solid #FE6C01;
      // box-sizing: border-box;
      // border-radius: 50%;
      margin-right: 8px;
      background-image: url('../../assets/images/gzq/icon-xm.png');
      background-repeat: no-repeat;
      background-size: 10px;
      width: 10px;
      height: 10px;
      // border-top: 9px solid transparent;
      // border-bottom: 9px solid transparent;
      // border-left: 8px solid #1E6FFF;
    }
  }
  /deep/.el-dialog__headerbtn{
    position: absolute;
    top: 16px;
    // transform: translateY(50%);
    width: 24px;
    height: 24px;
    background-repeat: no-repeat;
    background-position:center;
    background-size: 100% 100%;
  }
  /deep/.el-dialog__headerbtn .el-dialog__close{
    display: none;
  }
  /deep/.el-dialog__body {
    padding: 40px 24px;
    overflow: auto;
    max-height: 78vh;
    flex: 1;
    // background: #08141e;
  }
}
/deep/.el-row{
  display: flex;
  align-items: center;
}
.isHeader{
  /deep/.el-dialog__header{
    display: none!important;
  }
}
.imgSize{
  width: 24px;
  height: 24px;
  margin-left: 16px;
  cursor: pointer;
}
</style>
